package com.itheima.service.impl;

import org.springframework.stereotype.Service;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.Set;

/**
 * 用户服务
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;
    //根据用户名查询数据库中的用户信息，还需要查询用户关联的角色以及角色关联的权限
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);
        if(user != null){
            //根据用户id查询对应的角色
            Set<Role> roles = roleDao.findByUserId(user.getId());
            //遍历角色，查询对应的权限
            if(roles != null && roles.size() > 0){
                for (Role role : roles) {
                    //根据角色id查询对应的权限
                    Set<Permission> permissions = permissionDao.findByRoleId(role.getId());
                    role.setPermissions(permissions);
                }
            }
            user.setRoles(roles);
        }
        return user;
    }
}
